package com.store.orm.mysql.crud.impl;

import com.store.orm.mysql.MySQLUtil;
import com.store.orm.mysql.crud.filter.Filtration;
import com.store.orm.mysql.handler.ListRSHandler;
import com.store.orm.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.List;

import static com.store.orm.common.KeyWord.*;


/**
 * @author 宫静雨
 * @version 1.0
 */
public class PageSelect<T> {
    private static final Logger logger = LoggerFactory.getLogger(PageSelect.class);
    private MySQLUtil UTIL;
    private Integer pageNum;
    private Integer pageSize;
    private Class<T> cls;

    public PageSelect(MySQLUtil UTIL, Integer pageNum, Integer pageSize, Class<T> cls) {
        this.UTIL = UTIL;
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.cls = cls;
    }

    public List<T> page(Filtration filtration, String... fields) {
        String tableName = UTIL.getTableName(cls);
        StringBuilder sb = new StringBuilder();
        sb.append(SELECT);
        for (int i = 0; i < fields.length; i++) {
            sb.append(fields[i]);
            if (i != fields.length - 1) {
                sb.append(COMMA);
            }
        }
        sb.append(FROM).append(tableName);
        String str = filtration.get();
        if (!StringUtil.isBlank(str)) {
            sb.append(str);
        }
        this.pageNum = (this.pageNum - 1) * this.pageSize;
        String sql = sb.append(LIMIT).append(this.pageNum).append(COMMA).append(this.pageSize).toString();
        Connection connection = UTIL.getConnection();
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet resultSet = ps.executeQuery();
            if (UTIL.isLogged()) {
                logger.info(">>> {}", sql);
            }
            return new ListRSHandler(UTIL).handler(resultSet, cls);
        } catch (SQLException e) {
            logger.error("分页查询结果时发生错误: {}", e.getMessage());
        }
        return null;
    }

    public List<T> page(Filtration filtration) {
        String tableName = UTIL.getTableName(cls);
        Field[] fields = cls.getDeclaredFields();
        String prefix = UTIL.prefix(tableName, fields);
        String filter = filtration.get();
        if (!StringUtil.isBlank(filter)) {
            prefix += filter;
        }
        this.pageNum = (this.pageNum - 1) * this.pageSize;
        String sql = prefix + LIMIT + this.pageNum + COMMA + this.pageSize;
        Connection connection = UTIL.getConnection();
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet resultSet = ps.executeQuery();
            if (UTIL.isLogged()) {
                logger.info(">>> {}", sql);
            }
            return new ListRSHandler(UTIL).handler(resultSet, cls);
        } catch (SQLException e) {
            logger.error("分页查询结果时发生错误: {}", e.getMessage());
        }
        return null;
    }

    public Long count() {
        String sql = SELECT + COUNT + "(*) AS COUNT" + FROM + UTIL.getTableName(cls);
        try {
            Connection connection = UTIL.getConnection();
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet resultSet = ps.executeQuery();
            if (UTIL.isLogged()) {
                logger.info(">>> {}", sql);
            }
            if (resultSet.next()) {
                return resultSet.getLong(1);
            }
        } catch (SQLException e) {
            logger.error("分页查询数量时发生错误{}", e.getMessage());
        }
        return 0L;
    }
}